package com.fz.crowdfunding.interceptor;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fz.crowdfunding.bean.Permission;
import com.fz.crowdfunding.manager.service.PermissionService;
import com.fz.crowdfunding.util.Const;

public class AuthInterceptor extends HandlerInterceptorAdapter{
	
	@Autowired
	private PermissionService permissionService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		/*//1.查询所有许可
		List<Permission> queryAllPermission = permissionService.queryAllPermission();
		Set<String> allURIs = new HashSet<String>();
		for (Permission permission : queryAllPermission) {
			allURIs.add("/"+permission.getUrl());
		}*/
		
		//直接从application域中获取所有许可路径(StartSystemListener监听器启动时将许可路径放入application)
		Set allURIs = (Set)request.getSession().getServletContext().getAttribute(Const.ALL_PERMISSION_URI);
		//2.判断请求路径是否在许可范围内，不在范围内则放行
		String servletPath = request.getServletPath();
		if(allURIs.contains(servletPath)){
			//3.判断请求路径是否是用户所拥有的权限内
			//获取登录时存入session的用户可以访问的Url地址
			Set myUris = (Set) request.getSession().getAttribute(Const.MY_URIS);
			//如果请求地址在用户可以访问的Url地址内则放行，否则拦截
			if(myUris.contains(servletPath)){
				return true;
			}else{
				response.sendRedirect(request.getContextPath()+"/login.htm");
				return false;
			}
		}else{
			return true;
		}
	}
}
